<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName"></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select placeholder="请选择" v-model="spuParams.tmId">
                    <el-option :label="trademark.tmName" :value="trademark.id" v-for="(trademark,index) in allTradeMarkArr" :key="trademark.id"></el-option>
                  
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input placeholder="请输入SPU描述" type="textarea" v-model="spuParams.description"></el-input>

            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload
                v-model:file-list="imgListArr"
                action="/api/admin/product/fileUpload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
        

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select :placeholder="unSelectSaleAttr.length>0?`还有${unSelectSaleAttr.length}条数据没有选择` : `没有什么能选择的了`" v-model="unSaleAttrIdAndName" >
                    <el-option :label="sale.name" :value="`${sale.id}:${sale.name}`" v-for="(sale,index) in unSelectSaleAttr" :key="sale.id"></el-option>
                </el-select>
                <el-button type="primary" size="default" :icon="Plus" @click="addSaleAttr" :disabled="!unSaleAttrIdAndName">添加销售属性</el-button>

                <el-table border stripe style="margin: 10px 0px" :data="spuHasSaleAttrArr">
                    <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
                    <el-table-column label="属性名" width="120" prop="saleAttrName"></el-table-column>
                    <el-table-column label="属性值名称列表">
                        <template v-slot="{row,$index}">
                            <el-tag style="margin:0px 3px" v-for="(saleValue,index) in row.spuSaleAttrValueList" :key="saleValue.id" type="danger" closable @close="row.spuSaleAttrValueList.splice(index,1)">{{ saleValue.saleAttrValueName }}</el-tag>
                            <el-input placeholder="请输入" size="small" style="width:80px" v-if="row.flag" @blur="toLook(row)" v-model="row.inputValue"></el-input>
                            <el-button type="primary" size="small" @click="toEdit(row)" :icon="Plus" v-else ></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #="{row,$index}">
                            <el-button type="danger" size="default" @click="spuHasSaleAttrArr.splice($index,1)" :icon="Delete"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-button type="primary" size="default" @click="save">保存</el-button>
                <el-button size="default" @click="cancel">取消</el-button>

            </el-form-item>

        </el-form>

    </div>


    <!-- <el-button type="primary" size="default" @click="emit('changeScene',0)">取消</el-button>   -->
</template>
<script setup lang="ts">

//引入组合式API
import { ref,computed} from "vue";
//引入icom图标
import { Plus,Delete } from "@element-plus/icons-vue";
//引入数据类型
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";

//引入请求函数
import { reqAllaTradeMark, reqAllSaleAttr, reqImgList, reqSpuHasSaleAttr,reqAddOrUpdateSpu } from "@/api/product/spu/spu";
//储存响应服务器返回的数据：四个数组

//SPU下的全部品牌数据
let allTradeMarkArr = ref([]);
//获取已有SPU下照片墙的数据
let imgListArr = ref([]);
//获取已有SPU，携带的销售属性
let spuHasSaleAttrArr = ref([]);
//获取全部销售属性【任何情况最多就三个销售属性】
let allSaleAttrArr = ref([]);
//定义添加或修改spu数据
let spuParams = ref({});
//收集还未选择的销售属性
let unSaleAttrIdAndName = ref('');
//照片墙相关的代码
//存储预览图片地址
const dialogImageUrl = ref("");
//控制对话框显示与隐藏
const dialogVisible = ref(false);

//删除图片回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
};
//预览回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};
//图片上传成功的回调
const handleSuccess = (response,uploadFile,uploadFiles)=>{
  //前两个参数:图片上传成功的信息
  //最后的参数:图片上传成功以后，照片墙全部图片数据
  imgListArr.value = uploadFiles
}
//提供一个方法：将来父组件可以借用此方法来做传递数据
const initHasSpuData = async (spu:any) => {
    console.log(spu);
    //父组件传递过来的数据
    spuParams.value = spu
    //在父组件点击修改SPU按钮的时候，触发子组件当前方法，想服务器发送四个请求，获取全部品牌的数据
    let ps1 = reqAllaTradeMark();
    //获取已有SPU照片墙的数据
    let ps2 = reqImgList(spu.id);
    //获取当前SPU已有销售属性
    let ps3 = reqSpuHasSaleAttr(spu.id);
    //获取全部销售属性
    let ps4 = reqAllSaleAttr();
    //获取全部服务器返回数据
    let result = await Promise.all([ps1, ps2, ps3, ps4]);
    //存储全部品牌
    allTradeMarkArr.value = result[0];
    //存储照片墙的数据
    imgListArr.value = result[1];
    //存储已有销售属性
    spuHasSaleAttrArr.value = result[2];
    //获取全部销售属性
    allSaleAttrArr.value = result[3];
    //储存照片墙的数据
    //服务器返回的数据和UI组件库中的不一致需要修改
    imgListArr.value = result[1].map(item=>{
        return {
            name:item.imgName,
            url:item.imgUrl
        }
    })
};
//计算出SPU还没选择销售属性
let unSelectSaleAttr = computed(()=>{
    //过滤需要的数组
    let result = allSaleAttrArr.value.filter(item=>{
        return spuHasSaleAttrArr.value.every((item1)=>{
            return item.name != item1.saleAttrName;
        })
    })
    return result;
});
//销售属性点击添加事件回调函数
const addSaleAttr = () =>{
    //新增的销售属性ID和名字
    const [baseSaleAttrId,saleAttrName] = unSaleAttrIdAndName.value.split(':');
    //服务器需要的销售属性
    let newSaleAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]};
    //追加属性
    spuHasSaleAttrArr.value.push(newSaleAttr);
    //清空下拉框内容
    unSaleAttrIdAndName.value = '';
};
//点击属性值添加按钮
const toEdit = (row) =>{
    row.flag = true
    //给追加的数据一个空地
    row.inputValue = ''

};
//清空数据
const resetData = () =>{
    spuParams.value = {};
    imgListArr.value = [];
    spuHasSaleAttrArr.value = []
}
//编辑模式失去焦点切换查看模式
const toLook = (row) =>{
    //属性值不能为空
    if(row.inputValue.trim() == '') {
        //提示
        ElMessage({
            type:'error',
            message:'请不要不输入内容哦！'
        });
        // row.flag = false
        return
    }
    //属性不能重复
    let repeat = row.spuSaleAttrValueList.find(item=>{
        return item.saleAttrValueName === row.inputValue
    });
    //如果重复出现后面代码不能执行，再提示错误
    if(repeat){
        ElMessage({
            type:'error',
            message:'请不要重复输入内容哦！'
        });
            //清空最新同名属性值
        row.inputValue = ''
    //出现属性值同名切换button
    row.flag = false;
     return
    }
    //显示button设置
    row.flag = false;
    //新增属性值
    let newSaleattrVal = {
        baseSaleAttrId : row.baseSaleAttrId,    
        saleAttrValueName : row.inputValue
    }
    //追加属性值到数组中
    row.spuSaleAttrValueList.push(newSaleattrVal)
    //清空收集数组数据
    row.inputValue = '';
};
//点击保存，整理数据发请求
const save = async () =>{
    //整理照片墙数据
    //照片墙数据和系统数据不一致需要转换
    spuParams.value.spuImageList = imgListArr.value.map((item)=>{
        return {
            //名字转换
            imgName:item.name,
            //图片地址转换，分两种，已有图片和最新上传图片
            imgUrl:(item.response && item.response.data) || item.url,
        };

    });
    //整理销售属性的参数
    spuParams.value.spuSaleAttrList = spuHasSaleAttrArr.value;
    //再次发送请求：添加或修改的请求
    try {
        await reqAddOrUpdateSpu(spuParams.value);
        ElMessage({
            type:'success',
            message:spuParams.value.id ? '修改成功' : '添加成功',
        });
        //触发自定义事件
        emit('changeScene',{
            scenes:0,
            flag:spuParams.value.id ? 'update' : 'add',
        });
        //清空数据
        // resetData();
    } catch (error) {
        ElMessage({
            type:'error',
            message:spuParams.value.id ? '修改失败' : '添加失败'
        })
    }
};
//取消按钮事件回调
const cancel = () =>{
    emit('changeScene',{
        scenes:0,
        flag:spuParams.value.id ? "upda" : 'add'
    });
    resetData();
};
//点击添加SPU的时候，当前子组件发请求，获取全部品牌和获取全部销售属性
const initAddSpu = async(c3Id:string|number) => {
    //添加SPU追加三级分类ID
    spuParams.value.category3Id = c3Id;
    //获取全部品牌数据
    let ps1 =reqAllaTradeMark();
    //获取全部销售属性
    let ps2 = reqAllSaleAttr();
    let result = await Promise.all([ps1,ps2]);
    //储存全部品
    allTradeMarkArr.value = result[0];
    //获取全部销售属性
    allSaleAttrArr.value = result[1];
};
//触发自定义事件
let emit = defineEmits(['changeScene'])
//对外暴露方法数据
defineExpose({
    initHasSpuData,
    initAddSpu,
})
</script>

<style scoped>

</style>